package org.geekbang.projects.injection.jmx;

import org.apache.commons.collections4.MapUtils;
import org.geektimes.base.util.ReflectionUtils;

import javax.management.*;
import java.lang.management.ManagementFactory;
import java.util.Hashtable;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author : KangNing Hu
*/
public class JMXBeanSupport {

	private static final Logger logger = Logger.getLogger(JMXBeanSupport.class.getName());

	private  MBeanServer server;


	public JMXBeanSupport(){
		this.server =  ManagementFactory.getPlatformMBeanServer();
	}

	/**
	 * 注册Mbean
	 */
	protected void register(Object bean){
		Class<?> aClass = bean.getClass();
		MBeanRegister mBeanRegister = ReflectionUtils.getAnnotation(aClass, MBeanRegister.class);
		if (mBeanRegister != null){
			PropertiesLoader propertiesLoader = ReflectionUtils.newInstance(mBeanRegister.propertiesLoader());
			register(mBeanRegister.domain() ,propertiesLoader.load() ,  bean);
		}
	}


	/**
	 * 注册bean
	 * @param domain
	 * @param properties
	 * @param mBean
	 */
	protected void register(String domain , Map<String , String> properties , Object mBean){

		try {
			ObjectName objectName;
			if (!MapUtils.isEmpty(properties)){
				objectName = new ObjectName(domain, new Hashtable<>(properties));
			}else {
				objectName = new ObjectName(domain);
			}

			server.registerMBean(mBean, objectName);
			logger.log(Level.INFO , String.format("注册MBean[%s:%s]成功" , domain ,mBean.getClass().getTypeName()));
		}catch (Exception e){
			throw new IllegalStateException(e);
		}
	}
}
